package com.xwt.web.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.xwt.web.jwt.JwtConfigProperty;
import com.xwt.web.jwt.JwtUtil;

/**
 * 每次用户名密码验证后刷新token,适用于token过期时间较短的场景<br>
 * 缺点:每次请求都要刷新，增加服务器功耗,前端所存储的token也要每次重新赋值
 * 
 * @author Administrator
 *
 */
@Component
public class JwtSuccessTokenFilter extends OncePerRequestFilter {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private JwtConfigProperty jwtConfig;
	@Autowired
	private JwtUtil jwtUtil;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String tokenHead = this.jwtConfig.getTokenHead();
		try {
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		String token = jwtUtil.generateToken(username);
		response.setHeader(this.jwtConfig.getHeader(), tokenHead + token);
		logger.info(getClass().getName()+":"+username);
		}catch (Exception e) {
			response.getWriter().write("验证失败");
		}
		filterChain.doFilter(request, response);
	}

}
